package com.baigt.jvm.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 类功能描述:
 *
 * @author baigt
 * @version V1.0
 * @since 2019-07-14 15:04
 */
public class _003SaleTrainTicket2 {
    public static void main(String[] args) {
                final SaleRunnable runnable = new SaleRunnable();
//        final SaleRunnable2 runnable = new SaleRunnable2();
        new Thread(runnable, "柜台1").start();
        new Thread(runnable, "柜台2").start();
        new Thread(runnable, "柜台3").start();
    }

    public static void sleep() {
        try {
            TimeUnit.MILLISECONDS.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

/**
 * 下边的线程有什么问题？可以保证执行结果的正确性吗？
 * 怎么处理？
 */
class SaleRunnable implements Runnable {
    private static final int ticketNum = 50;
    private static int index = 1;

    @Override
    public void run() {
        while (index <= ticketNum) {
            System.out.println("" + Thread.currentThread().getName() + "sale:" + index++);
//            _003SaleTrainTicket2.sleep();
        }
    }
}
/**
 * 下边的线程有什么问题？可以保证执行结果的正确性吗？
 * 怎么处理？
 */
/**
 * 下边的线程有什么问题？可以保证执行结果的正确性吗？
 */
class SaleRunnable2 implements Runnable {
    private static final int ticketNum = 50;
    //    private static int index = 1;
    private static AtomicInteger index = new AtomicInteger(0);

    @Override
    public void run() {
        int tmp;
        while ((tmp=index.incrementAndGet()) <= ticketNum) {
            System.out.println("" + Thread.currentThread().getName() + "sale:" + tmp);
            _003SaleTrainTicket2.sleep();
        }
    }
}
